package com.hula.onion.book.server.spider.platforms.xinyongbao;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import com.hula.onion.book.server.spider.platforms.xiangshangjinfu.XiangShangJinFuSpiderHelper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/1/22.
 */
@Component
public class XinYongBaoSpiderHelper {

    private static final Logger logger = LoggerFactory.getLogger(XiangShangJinFuSpiderHelper.class);

    public Map<String, Object> installRequestParams(LoginForm loginForm) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("username", loginForm.getUserName());
        map.put("pwd", loginForm.getPassword());
        map.put("errorCount", "0");
        map.put("vcode", "");
        return map;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }

        try {
            AccountInfo accountInfo = new AccountInfo();
            Document document = Jsoup.parse(html);
            Element amountElement = document.selectFirst("dl.all-property");
            String amount = amountElement.getAllElements().get(6).text();
            Element wIElement = document.selectFirst("dl.all-property-detail");
            String waitIntrest = wIElement.getAllElements().get(8).text();
            Element tIElement = document.selectFirst("dl.all-earn");
            String totalIntrest = tIElement.getAllElements().get(20).text();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setWaitIntrest(new BigDecimal(waitIntrest));
            accountInfo.setTotalIntrest(new BigDecimal(totalIntrest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            logger.error("[XinYongBaoSpiderHelper] parseAccountBalance fail!", e);
        }
        return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
    }

}
